package com.itheima.sfbx.insurance.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.sfbx.framework.commons.constant.basic.SuperConstant;
import com.itheima.sfbx.framework.commons.exception.ProjectException;
import com.itheima.sfbx.framework.commons.utils.BeanConv;
import com.itheima.sfbx.insurance.constant.SafeguardCacheConstant;
import com.itheima.sfbx.insurance.dto.SafeguardVO;
import com.itheima.sfbx.insurance.enums.SafeguardEnum;
import com.itheima.sfbx.insurance.mapper.SafeguardMapper;
import com.itheima.sfbx.insurance.pojo.CategorySafeguard;
import com.itheima.sfbx.insurance.pojo.PlanSafeguard;
import com.itheima.sfbx.insurance.pojo.Safeguard;
import com.itheima.sfbx.insurance.service.ICategorySafeguardService;
import com.itheima.sfbx.insurance.service.IPlanSafeguardService;
import com.itheima.sfbx.insurance.service.ISafeguardService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Description：保障项服务实现类
 */
@Slf4j
@Service
public class SafeguardServiceImpl extends ServiceImpl<SafeguardMapper, Safeguard> implements ISafeguardService {
    @Autowired
    private ICategorySafeguardService categorySafeguardService;
    @Autowired
    private IPlanSafeguardService planSafeguardService;
    private LambdaQueryWrapper<Safeguard> queryWrqpper(SafeguardVO safeguardVO){
        LambdaQueryWrapper<Safeguard> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(safeguardVO.getSafeguardKey()),Safeguard::getSafeguardKey,safeguardVO.getSafeguardKey())
                .like(StrUtil.isNotBlank(safeguardVO.getSafeguardKeyName()),Safeguard::getSafeguardKeyName,safeguardVO.getSafeguardKeyName())
                .eq(StrUtil.isNotBlank(safeguardVO.getDataState()),Safeguard::getDataState,safeguardVO.getDataState());
        return wrapper;
    }

    @Override
    @Cacheable(value = SafeguardCacheConstant.PAGE,key = "#pageNum+'-'+#pageSize+'-'+#safeguardVO.hashCode()")
    public Page<SafeguardVO> findPage(SafeguardVO safeguardVO, int pageNum, int pageSize) {
        //构建分页查询条件器
        LambdaQueryWrapper<Safeguard> wrapper = queryWrqpper(safeguardVO);
        //分页查询
        Page<Safeguard> page = this.page(new Page<>(pageNum, pageSize), wrapper);
        //转为返回值类型
        Page<SafeguardVO> voPage = BeanConv.toPage(page, SafeguardVO.class);
        return voPage;
    }

    @Override
    @Cacheable(value = SafeguardCacheConstant.BASIC,key = "#safeguardId")
    public SafeguardVO findById(String safeguardId) {
        Safeguard safeguard = this.getById(safeguardId);
        if(safeguard==null){
            return null;
        }
        return BeanConv.toBean(safeguard,SafeguardVO.class);
    }

    @Override
    @Transactional
    @Caching(
            evict = {@CacheEvict(value =SafeguardCacheConstant.PAGE,allEntries = true),
                    @CacheEvict(value =SafeguardCacheConstant.LIST,allEntries = true)},
            put=@CachePut(value = SafeguardCacheConstant.BASIC,key = "#result.id")
    )
    public SafeguardVO save(SafeguardVO safeguardVO) {
        //保障项编号是否存在
        Integer count = this.lambdaQuery()
                .eq(Safeguard::getSafeguardKey, safeguardVO.getSafeguardKey())
                .eq(Safeguard::getDataState, SuperConstant.DATA_STATE_0)
                .count();
        if(count>0){
            throw new ProjectException(SafeguardEnum.SAVE_FAIL);
        }
        Safeguard safeguard = BeanConv.toBean(safeguardVO, Safeguard.class);
        this.save(safeguard);
        return BeanConv.toBean(safeguard, SafeguardVO.class);
    }

    @Override
    @Transactional
    @Caching(
            evict = {@CacheEvict(value =SafeguardCacheConstant.PAGE,allEntries = true),
                    @CacheEvict(value =SafeguardCacheConstant.LIST,allEntries = true),
                    @CacheEvict(value = SafeguardCacheConstant.BASIC,key = "#safeguardVO.id")
            }
    )
    public Boolean update(SafeguardVO safeguardVO) {
        //查询保障项是否存在
        Safeguard safeguard = this.getById(safeguardVO.getId());
        if(safeguard==null){
            throw new ProjectException(SafeguardEnum.UPDATE_FAIL);
        }
        //查询保障项编号是否存在
        Integer count = this.lambdaQuery()
                .eq(Safeguard::getSafeguardKey, safeguardVO.getSafeguardKey())
                .eq(Safeguard::getDataState, SuperConstant.DATA_STATE_0)
                .ne(Safeguard::getId,safeguardVO.getId())
                .count();
        if(count>0){
            throw new ProjectException(SafeguardEnum.UPDATE_FAIL);
        }
      //查询是否与原保障项key有关联关系
        Integer count1 = categorySafeguardService.lambdaQuery()
                .eq(CategorySafeguard::getSafeguardKey, safeguard.getSafeguardKey())
                .count();
        Integer count2 = planSafeguardService.lambdaQuery()
                .eq(PlanSafeguard::getSafeguardKey, safeguard.getSafeguardKey())
                .count();
        //有关系不能修改
        if(count1>0||count2>0){
            throw new ProjectException(SafeguardEnum.UPDATE_FAIL);
        }
        return this.updateById(BeanConv.toBean(safeguardVO, Safeguard.class));
    }

    @Override
    @Transactional
    @Caching(
            evict = {@CacheEvict(value =SafeguardCacheConstant.PAGE,allEntries = true),
                    @CacheEvict(value =SafeguardCacheConstant.LIST,allEntries = true),
                    @CacheEvict(value = SafeguardCacheConstant.BASIC,allEntries = true)
            }
    )
    public Boolean delete(String[] checkedIds) {
        List<String> ids = Arrays.asList(checkedIds);

        //查询是否存在
        List<Safeguard> list = this.lambdaQuery()
                .in(Safeguard::getId, ids)
                .list();

        //不存在
        if(CollUtil.isEmpty(list)){
            return true;
        }
        //存在
        //查询是否与保障项key有关联关系
        Set<String> set = list.stream().map(Safeguard::getSafeguardKey).collect(Collectors.toSet());
        Integer count1 = categorySafeguardService.lambdaQuery()
                .in(CategorySafeguard::getSafeguardKey, set)
                .count();
        Integer count2 = planSafeguardService.lambdaQuery()
                .in(PlanSafeguard::getSafeguardKey, set)
                .count();
        if(count1>0||count2>0){
            throw new ProjectException(SafeguardEnum.DEL_FAIL);
        }
        return this.removeByIds(ids);
    }

    @Override
    @Cacheable(value = SafeguardCacheConstant.LIST,key = "#safeguardVO.hashCode()")
    public List<SafeguardVO> findList(SafeguardVO safeguardVO) {
        LambdaQueryWrapper<Safeguard> wrapper = queryWrqpper(safeguardVO);
        List<Safeguard> list = this.list(wrapper);
        if(list==null){
            throw new RuntimeException("查询失败");
        }
        List<SafeguardVO> voList = BeanConv.toBeanList(list, SafeguardVO.class);
        return voList;
    }


    @Override
    public List<SafeguardVO> findShowPageItemByKey(List<String> safeguardKeyList) {
        //TODO
        return null;
    }

    @Override
    @Cacheable(value = SafeguardCacheConstant.BASIC,key = "#result.id")
    public SafeguardVO findBySafeguardKey(String safeguardKey) {
        if(safeguardKey==null){
            return null;
        }
        Safeguard safeguard = this.lambdaQuery().eq(Safeguard::getSafeguardKey, safeguardKey)
                .one();
        if(safeguard==null){
            return null;
        }

        return BeanConv.toBean(safeguard, SafeguardVO.class);
    }
}
